package com.flute.framework.index.fieldbuilder;

import org.apache.lucene.document.Field;

import com.flute.framework.index.analysis.PayloadTokenizer;
import com.flute.framework.index.analysis.SpliterTokenizer;
import com.flute.framework.search.sort.ScoreUtil;
import com.flute.framework.stringprocessor.IStringProcessor;
import com.flute.tools.data.DataRecord;
import com.flute.tools.util.StringUtil;

public class LuceneScoreFieldBuilder extends AbstractFieldBuilder {
	protected IStringProcessor processor;

	@Override
	public Object buildField(DataRecord record) {
		ScoreField sf = new ScoreField();

		String field = getDataField();
		String value = record.getFieldValue(field);
		if (value == null) {
			value = "";
		}
		value = StringUtil.getStandardString(value);
		sf.setText(value);

		String[] ss = processor.process(value).trim().split(
				String.valueOf(SpliterTokenizer.SPLITER));
		for (String s : ss) {
			sf.addString(s);
			sf.addScore(s, getDefaultScore(s, value));
		}

		return new Field(docField, new PayloadTokenizer(sf));
	}

	protected SorterScore getDefaultScore(String term, String text) {
		SorterScore ss = new SorterScore();
		ss.setSorterName(ScoreField.DEFAULT_SCORE);
		if (text.contains(term)) {
			ss.setScore(ScoreUtil.getWordDefaultScore(text, term) * 5000);
		}
		return ss;
	}

	public IStringProcessor getProcessor() {
		return processor;
	}

	public void setProcessor(IStringProcessor processor) {
		this.processor = processor;
	}
}
